<?php

global $_W, $_GPC;

//error_reporting(2047);

@set_time_limit(0);
@ini_set('memory_limit', '4096M');
/*@ini_set('display_errors', '1');
@error_reporting(E_ALL ^ E_NOTICE);*/

include_once IA_ROOT . '/addons/ewei_shop/core/inc/plugin/plugin.php';

if(!empty($_GPC['ok'])){
    echo 'ok';
    exit();
}

/*$page = !empty($_GPC['page']) ? $_GPC['page'] : 1;
$pindex = max(1, $page);
$psize = 200;
//$sql = 'SELECT `openid` FROM '.tablename('ewei_shop_member').' WHERE `isagent` = 1 AND `status` = 1 ORDER BY `id` ASC LIMIT 1';

$sql = 'SELECT `openid` FROM '.tablename('ewei_shop_member').' WHERE `isagent` = 1 AND `status` = 1 ORDER BY `id` ASC LIMIT '.($pindex - 1) * $psize .' , ' .$psize;
$members = pdo_fetchall($sql);*/

echo 'qianyu v2 - am';
exit();

$members = array();

$members[] = array(
    'id' => '374',
    'openid' => 'os6zfw1YCsz_ua0ilukZMOVMYxqs'
);

if(!empty($members)){

    foreach($members as $member){

        $pluginModel = new Plugin('commission');

        $base = $pluginModel->model->getAllNextMembers($member['openid'], true)->getAllSalesvolumes()->getAllWealths()->getDetail();

        echo '<pre>';

        $wealths = $base->wealthsPrice;
        echo round($wealths['padding'] + $wealths['unapply'] + $wealths['play'] + $wealths['invalid'] + $wealths['apply'] + $wealths['applyed'], 2);

        echo '<br />';

        // ( TOTAL = 总额， OK = 可提现， LOCK = 待提现， APPLY = 正在申请，CHECK = 已审核, PAY = 已支付 )
        $res = $pluginModel->model->getCommissionRecordPrice($member['id'], array('total', 'ok', 'lock', 'apply', 'check', 'pay', 'invalid'));

        var_dump($res);

        exit();

        if(!empty($base->records)){

            try{
                pdo_begin();

                foreach($base->records as $item){
                    pdo_insert('ewei_shop_commission_record', $item);
                }

                pdo_commit();

            }catch(PDOException $e){

                pdo_rollback();

                echo $e->getMessage();
            }
        }

        unset($pluginModel, $base);
    }

}else{
    message('迁移已经完成：' . $pindex * $psize, $this->createWebUrl('test', array('ok' => 1)), 'info');
}

message('迁移中，已经完成：' . $pindex * $psize, $this->createWebUrl('test', array('page' => $pindex+1)), 'info');

exit();

if(!empty($base->records)){

    try{
        pdo_begin();

        foreach($base->records as $item){
            pdo_insert('ewei_shop_commission_record', $item);
        }

        pdo_commit();

    }catch(PDOException $e){

        pdo_rollback();

        echo $e->getMessage();
    }
}

echo 'ok';

exit();

echo '<pre>';
var_dump($wealths);

echo '<hr />';
$res = $this->model->getCommissionRecordPrice($openid, array('total', 'ok', 'pay'));

var_dump($res);



$level1 = $base->afterSalesVolumesLevel['level1']['finish'];
$level2 = $base->afterSalesVolumesLevel['level2']['finish'];
$level3 = $base->afterSalesVolumesLevel['level3']['finish'];

echo count($level1) + count($level2) + count($level3);

exit();

if(!empty($level1)){

    try{
        pdo_begin();

    foreach($level1 as $item){
        $res = record($member, $item, 1);

        if($res !== false){
            pdo_insert('ewei_shop_commission_record', $res);
        }
    }

    pdo_commit();
}catch(PDOException $e){
    pdo_rollback();

    echo $e->getMessage();
}

}

if(!empty($level2)){

    try{
        pdo_begin();

        foreach($level2 as $item){
            $res = record($member, $item, 2);

            if($res !== false){
                pdo_insert('ewei_shop_commission_record', $res);
            }
        }

        pdo_commit();
    }catch(PDOException $e){
        pdo_rollback();

        echo $e->getMessage();
    }

}

if(!empty($level3)){

    try{
        pdo_begin();

        foreach($level3 as $item){
            $res = record($member, $item, 3);

            if($res !== false){
                pdo_insert('ewei_shop_commission_record', $res);
            }
        }

        pdo_commit();
    }catch(PDOException $e){
        pdo_rollback();

        echo $e->getMessage();
    }

}

echo 'OK';


function record($member, $item, $level){
    global $_W;

    $sql = 'SELECT * FROM '.tablename('ewei_shop_order_goods').' WHERE `uniacid` = :uniacid ';
    $sql .= ' AND `orderid` = :oid ';
    $pam = array(':uniacid' => $_W['uniacid'], ':oid' => $item['id']);

    $orderGoods = pdo_fetch($sql, $pam);

    if(!empty($orderGoods)){
        $commission = $orderGoods["commission$level"];

        $agentlevel = $member['agentlevel'];
        if($member['upleveltime'] < $item['createtime']){
            $agentlevel = $member['oldlevel'];
        }

        $price = _salesVolumesPrice($commission, $agentlevel);

        $temp['c_money'] = $price;

        $temp['uniacid'] = $_W['uniacid'];
        $temp['mid'] = $member['id'];
        $temp['orderid'] = $orderGoods['orderid'];
        $temp['goods_id'] = $orderGoods['goodsid'];
        $temp['cg_money'] = $orderGoods['price'];

        $temp['o_create_time'] = $item['createtime'];
        $temp['o_send_time'] = $item['sendtime'];
        $temp['o_pay_time'] = $item['paytime'];
        $temp['o_finish_time'] = $item['finishtime'];
        $temp['o_status'] = $item['status'];

        $temp['c_rank'] = $level;
        $temp['c_type'] = 1;
        $temp['c_rate'] = 0;

        $temp['c_apply_time'] = $orderGoods['applytime' . $level];
        $temp['c_check_time'] = $orderGoods['checktime' . $level];
        $temp['c_pay_time'] = $orderGoods['paytime' . $level];
        $temp['c_invalid_time'] = $orderGoods['invalidtime' . $level];
        $temp['c_content'] = $orderGoods['content' . $level];
        $temp['c_status'] = $orderGoods['status' . $level];

        return $temp;
    }

    return false;
}

function _salesVolumesPrice($commission, $level){
    $commission = iunserializer($commission);
    $price = isset( $commission['level' . $level] ) ? $commission['level' . $level] : $commission['default'];

    return $price;
}


/*$res = $qianyiModel->getMemberInfo($agentid)->getRecord();

$res = array_merge($res['one'], $res['two'], $res['thr']);

try {

    pdo_begin();

    foreach ($res as $item) {
        pdo_insert('ewei_shop_commission_record', $item);
    }

    pdo_commit();

} catch (PDOException $e) {

    pdo_rollback();
    echo $e->getMessage();

}*/


/*
echo '<pre>';
echo '$memberOne > ','<br />';
var_dump($memberOne);
echo '$memberOne End > ','<br />';
echo '</pre>';

echo '<hr />';

echo '<pre>';
echo '$orderOne > ','<br />';
var_dump($orderOne);
echo '$orderOne END > ','<br />';
echo '</pre>';

echo '<hr />';

echo '<pre>';
echo '$orderGoodsOne > ','<br />';
var_dump($orderGoodsOne);
echo '$orderGoodsOne END> ','<br />';

echo '</pre>';
*/

exit();

$pindex = max(1, $_GPC['page']);
$psize = 2000;
/*
$sql  = 'SELECT o.id, o.openid, o.agentid, o.price, o.status, o.createtime, o.sendtime, o.paytime, o.finishtime, ';
$sql .= 'og.goodsid, og.price AS goodsprice, ';
$sql .= 'og.commission1, og.status1, og.applytime1, og.checktime1, og.paytime1, og.invalidtime1, og.content1,  ';
$sql .= 'og.commission2, og.status2, og.applytime2, og.checktime2, og.paytime2, og.invalidtime2, og.content2,  ';
$sql .= 'og.commission3, og.status3, og.applytime3, og.checktime3, og.paytime3, og.invalidtime3, og.content3  ';
$sql .= 'FROM '.tablename('ewei_shop_order').' AS o ';
$sql .= 'LEFT JOIN '.tablename('ewei_shop_order_goods').' AS og ON o.id = og.orderid ';
$sql .= 'WHERE o.uniacid = :uniacid AND o.status >= :status';

$results = pdo_fetchall($sql, array(':uniacid' => $_W['uniacid'], ':status' => 0));
*/

$sql = 'SELECT * FROM ' . tablename('ewei_shop_order');
$sql .= ' WHERE `uniacid` = :uniacid ORDER BY `createtime` ASC LIMIT ' . ( $pindex - 1 ) * $psize . ',' . $psize;

$orderLists = pdo_fetchall($sql, array( ':uniacid' => $_W['uniacid'] ), 'id');

if (empty( $orderLists )) {
    message('迁移完成A', '', 'success');
}

$sqlx = 'SELECT * FROM ' . tablename('ewei_shop_order_goods') . ' WHERE `orderid` in (' . implode(',', array_keys($orderLists)) . ')';
$orderGoods = pdo_fetchall($sqlx);

if (empty( $orderGoods )) {
    message('迁移完成B', '', 'success');
}

$res = array();

foreach ($orderGoods as $good) {

    $order = $orderLists[$good['orderid']];

    if (!empty( $order )) {

        $agents = array();

        if ($order['agentid'] != 0) {
            $agents = $this->model->getAgentx($order['agentid'], $order['createtime']);
        }

        $commissions = 0;

        foreach ($agents as $key => $agent) {
            $i = $key + 1;
            $temp = array();

            $commission = iunserializer($good['commission' . $i]);
            $agentLevel = $agent['agentlevel'];

            if (!empty( $agent['oldlevel'] ) && $agent['upleveltime'] < $order['createtime']) {
                $agentLevel = $agent['oldlevel'];
            }

            $temp['c_money'] = isset( $commission ['level' . $agentLevel] ) ? $commission ['level' . $agentLevel] : $commission ['default'];

            if ($temp['c_money'] <= 0) {
                continue;
            }

            $temp['uniacid'] = $_W['uniacid'];
            $temp['mid'] = $agent['id'];
            $temp['orderid'] = $good['orderid'];
            $temp['goods_id'] = $good['goodsid'];
            $temp['cg_money'] = $good['price'];

            $temp['o_create_time'] = $order['createtime'];
            $temp['o_send_time'] = $order['sendtime'];
            $temp['o_pay_time'] = $order['paytime'];
            $temp['o_finish_time'] = $order['finishtime'];
            $temp['o_status'] = $order['status'];

            $temp['c_rank'] = $i;
            $temp['c_type'] = 1;
            $temp['c_rate'] = 0;

            $temp['c_apply_time'] = $good['applytime' . $i];
            $temp['c_check_time'] = $good['checktime' . $i];
            $temp['c_pay_time'] = $good['paytime' . $i];
            $temp['c_invalid_time'] = $good['invalidtime' . $i];
            $temp['c_content'] = $good['content' . $i];
            $temp['c_status'] = $good['status' . $i];


            //pdo_insert('ewei_shop_commission_record', $temp);

            $res[] = $temp;
        }

    }

}


$r = $this->model->checkCalculateParams($res);

if ($r !== false) {

    try {

        pdo_begin();

        foreach ($res as $re) {
            pdo_insert('ewei_shop_commission_record', $re);
        }

        pdo_commit();

    } catch (PDOException $e) {
        pdo_rollback();
        return $e->getMessage();
    }

}


message('迁移中，已经完成：' . $pindex * $psize, $this->createPluginWebUrl('commission/test', array( 'page' => $pindex + 1 )), 'info');